import strHtml from "./AdminOrderPage.html";
import { DomUtils } from "../../utils/DomUtils";

export class AdminOrderPage {
  constructor() {
    this.dom = null;
    this.orderList = [
      {
        orderId: "202506011234567890",
        farmerName: "vivi",
        userName: "kk",
        totalAmount: "15.00",
        createTime: "202506011001",
        orderStatus: "已揽收",
        updateTime: "202506011530",
        trackingNumber: "SF1234567892",
        deliveryType: "普通配送",
        receiverInfo: {
          name: "张三",
          phone: "13800001111",
          email: "example@domain.com",
          address: "北京市朝阳区xx路xx号",
          detail: "1号楼2单元301",
        },
        productList: [{ name: "西红柿", quantity: 2 }],
        comments: [],
      },
      {
        orderId: "202506031234567891",
        farmerName: "vivi",
        userName: "kk",
        totalAmount: "22.00",
        createTime: "202506030901",
        orderStatus: "已签收",
        updateTime: "202506050800",
        trackingNumber: "SF1234567891",
        deliveryType: "普通配送",
        receiverInfo: {
          name: "张三",
          phone: "13800001111",
          email: "example@domain.com",
          address: "北京市朝阳区xx路xx号",
          detail: "1号楼2单元301",
        },
        productList: [{ name: "土豆", quantity: 3 }],
        comments: [],
      },
      {
        orderId: "202506031234567892",
        farmerName: "vivi",
        userName: "kk",
        totalAmount: "22.50",
        createTime: "202506050101",
        orderStatus: "已支付",
        updateTime: "",
        trackingNumber: "",
        deliveryType: "加急配送",
        receiverInfo: {
          name: "张三",
          phone: "13800001111",
          email: "example@domain.com",
          address: "北京市朝阳区xx路xx号",
          detail: "1号楼2单元301",
        },
        productList: [{ name: "西红柿", quantity: 5 }],
        comments: [],
      },
    ];
    this.table = null;
    this.orderModal = null;
    this.deleteConfirmModal = null;
    this.pendingDeleteId = null;
    console.log("🚨  =", this.orderList);
  }

  render() {
    this.dom = DomUtils.convertToDom(strHtml);
    this._bindEvents();
    this._initDataTable();
    return this.dom;
  }

  _bindEvents() {
    this.orderModal = new bootstrap.Modal(
      this.dom.querySelector("#orderModal")
    );
    this.deleteConfirmModal = new bootstrap.Modal(
      this.dom.querySelector("#deleteConfirmModal")
    );
    const form = this.dom.querySelector("#orderForm");

    // 保存（新增/修改）
    this.dom.querySelector("#saveUserBtn").addEventListener("click", () => {
      const orderId =
        form.querySelector("#orderId").value || String(Date.now());
      const farmerName = form.querySelector("#farmerName").value;
      const userName = form.querySelector("#userName").value;
      const totalAmount = form.querySelector("#totalAmount").value;
      const createTime = form.querySelector("#createTime").value;
      const orderStatus = form.querySelector("#orderStatust").value;
      //const updateTime = form.querySelector("#updateTime").value;
      const trackingNumber = form.querySelector("#trackingNumber").value;

      if (
        !orderId ||
        !farmerName ||
        !userName ||
        !totalAmount ||
        !createTime ||
        !orderStatus ||
        //!updateTime ||
        !trackingNumber
      ) {
        alert("请完整填写订单信息！");
        return;
      }

      const newOrder = {
        orderId,
        farmerName,
        userName,
        totalAmount,
        createTime,
        orderStatus,
        updateTime: new Date().toLocaleString(),
        trackingNumber,
      };
      const existingIndex = this.orderList.findIndex(
        (o) => o.orderId == orderId
      );

      if (existingIndex !== -1) {
        this.orderList[existingIndex] = {
          ...this.orderList[existingIndex],
          ...newOrder,
        };
      } else {
        this.orderList.push(newOrder);
      }

      this.orderModal.hide();
      this._refreshTable();
    });

    // 删除确认
    this.dom
      .querySelector("#confirmDeleteBtn")
      .addEventListener("click", () => {
        if (this.pendingDeleteId !== null) {
          this.orderList = this.orderList.filter(
            (o) => o.orderId != this.pendingDeleteId
          );
          this.pendingDeleteId = null;
          this.deleteConfirmModal.hide();
          this._refreshTable();
        }
      });
  }

  _initDataTable() {
    this.table = window
      .$(this.dom.querySelector("#basic-datatable"))
      .DataTable({
        data: this.orderList,
        lengthChange: false,
        columns: [
          { data: "orderId", title: "订单编号" },
          { data: "farmerName", title: "卖家" },
          { data: "userName", title: "买家" },
          {
            data: null,
            title: "商品信息",
            render: (data, type, row) => {
              return `<a href=\"#\" class=\"product-info-link\" data-id=\"${row.orderId}\">购买详情</a>`;
            },
          },
          { data: "totalAmount", title: "总金额" },
          {
            data: null,
            title: "收货信息",
            render: (data, type, row) => {
              return `<a href=\"#\" class=\"receiver-info-link\" data-id=\"${row.orderId}\">收货信息详情</a>`;
            },
          },
          {
            data: "orderStatus",
            title: "订单状态",
            render: (data, type, row) => {
              const statusMap = {
                已支付: "btn-warning",
                已发货: "btn-info",
                已揽收: "btn-primary",
                运输中: "btn-primary",
                派送中: "btn-primary",
                待收货: "btn-success",
                已签收: "btn-danger",
                待评价: "btn-danger",
                已评价: "btn-secondary",
              };
              const buttonClass = statusMap[data] || "btn-secondary";
              return `<button class=\"btn btn-sm ${buttonClass} status-btn\" data-id=\"${
                row.orderId
              }\" ${data === "已评价" ? "" : ""}>${data}</button>`;
            },
          },
          { data: "updateTime", title: "更新时间" },
          {
            data: null,
            title: "物流信息",
            render: (data, type, row) => {
              return `<a href=\"#\" class=\"logistics-info-link\" data-id=\"${row.orderId}\">物流详情</a>`;
            },
          },
          {
            data: null,
            title: "操作",
            orderable: false,
            render: (data, type, row) => {
              return `
              <button class=\"btn btn-sm btn-warning me-1 btn-edit\" data-id=\"${row.orderId}\">修改</button>
              <button class=\"btn btn-sm btn-danger btn-delete\" data-id=\"${row.orderId}\">删除</button>
            `;
            },
          },
        ],
        pageLength: 15,
        destroy: true,
      });

    this._bindRowEvents();
  }

  _refreshTable() {
    this.table.clear().rows.add(this.orderList).draw();
    this._bindRowEvents();
  }

  _bindRowEvents() {
    setTimeout(() => {
      const form = this.dom.querySelector("#orderForm");

      // 绑定状态按钮点击事件
      this.dom.querySelectorAll(".status-btn").forEach((btn) => {
        btn.addEventListener("click", (e) => {
          const id = e.target.dataset.id;
          const order = this.orderList.find((o) => o.orderId == id);
          const currentStatus = order.orderStatus;

          const statusFlow = {
            已支付: "已发货",
            已发货: "已揽收",
            已揽收: "运输中",
            运输中: "派送中",
            派送中: "待收货",
            待收货: "已签收",
          };

          if (currentStatus === "已签收") {
            // 只变成待评价，不弹窗
            order.orderStatus = "待评价";
            order.updateTime = new Date().toLocaleString();
            this._refreshTable();
            return;
          }
          if (currentStatus === "待评价") {
            order.orderStatus = "已评价";
            order.updateTime = new Date().toLocaleString();
            this._refreshTable();
          }
          if (currentStatus === "已评价") {
            // 弹出只读评价弹窗
            showCommentModal(order, true);
            return;
          }

          if (statusFlow[currentStatus]) {
            if (currentStatus === "已支付") {
              const trackingNumber = prompt("请输入物流单号：");
              if (!trackingNumber) {
                return;
              }
              order.trackingNumber = trackingNumber;
            }
            order.orderStatus = statusFlow[currentStatus];
            order.updateTime = new Date().toLocaleString();
            this._refreshTable();
          }
        });
      });

      this.dom.querySelectorAll(".btn-edit").forEach((btn) => {
        btn.addEventListener("click", (e) => {
          const id = e.target.dataset.id;
          const order = this.orderList.find((o) => o.orderId == id);

          form.querySelector("#orderId").value = order.orderId;
          form.querySelector("#farmerName").value = order.farmerName;
          form.querySelector("#userName").value = order.userName;
          form.querySelector("#totalAmount").value = order.totalAmount;
          form.querySelector("#createTime").value = order.createTime;
          form.querySelector("#orderStatust").value = order.orderStatus;
          //form.querySelector("#updateTime").value = order.updateTime;
          form.querySelector("#trackingNumber").value = order.trackingNumber;

          this.orderModal.show();
        });
      });

      this.dom.querySelectorAll(".btn-delete").forEach((btn) => {
        btn.addEventListener("click", (e) => {
          this.pendingDeleteId = e.target.dataset.id;
          this.deleteConfirmModal.show();
        });
      });

      // 绑定收货信息详情弹窗
      this.dom.querySelectorAll(".receiver-info-link").forEach((link) => {
        link.addEventListener("click", (e) => {
          e.preventDefault();
          const id = e.target.dataset.id;
          const order = this.orderList.find((o) => o.orderId == id);
          const info = order.receiverInfo;
          alert(
            `收件人：${info.name}\n电话：${info.phone}\n邮箱：${info.email}\n收货地址：${info.address}\n详细地址：${info.detail}`
          );
        });
      });
      // 绑定商品详情弹窗
      this.dom.querySelectorAll(".product-info-link").forEach((link) => {
        link.addEventListener("click", (e) => {
          e.preventDefault();
          const id = e.target.dataset.id;
          const order = this.orderList.find((o) => o.orderId == id);
          const products = order.productList
            .map((p) => `${p.name} × ${p.quantity}`)
            .join("\n");
          alert(`商品明细：\n${products}`);
        });
      });
      // 绑定物流信息详情弹窗
      this.dom.querySelectorAll(".logistics-info-link").forEach((link) => {
        link.addEventListener("click", (e) => {
          e.preventDefault();
          const id = e.target.dataset.id;
          const order = this.orderList.find((o) => o.orderId == id);
          alert(
            `物流单号：${order.trackingNumber}\n配送方式：${order.deliveryType}`
          );
        });
      });
    }, 0);
  }
}

function showCommentModal(order, readOnly, onSubmit) {
  let modal = document.getElementById("commentModal");
  if (!modal) {
    // 直接插入到body，且只创建一次
    document.body.insertAdjacentHTML(
      "beforeend",
      `
      <div class="modal fade" id="commentModal" tabindex="-1" aria-labelledby="commentModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="commentModalLabel">订单评价</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body" id="commentModalBody"></div>
            <div class="modal-footer" id="commentModalFooter"></div>
          </div>
        </div>
      </div>
    `
    );
    modal = document.getElementById("commentModal");
  }
  // 填充内容
  const body = modal.querySelector("#commentModalBody");
  const footer = modal.querySelector("#commentModalFooter");
  if (readOnly) {
    if (!order.comments || order.comments.length === 0) {
      body.innerHTML = '<div class="text-center text-muted">暂无评价</div>';
    } else {
      body.innerHTML = order.comments
        .map(
          (c) => `
        <div class=\"d-flex align-items-start mb-3\">
          <img src=\"${c.avatar}\" style=\"width:40px;height:40px;border-radius:50%;object-fit:cover;\">
          <div class=\"ms-2 flex-grow-1\">
            <div><strong>${c.nickname}</strong></div>
            <div class=\"text-muted small\">${c.time}</div>
            <div class=\"mt-1\">${c.content}</div>
          </div>
        </div>
      `
        )
        .join("");
    }
    footer.innerHTML = "";
  } else {
    // 可编辑
    body.innerHTML = `<textarea class="form-control" id="commentContent" rows="4" placeholder="请输入评价内容..."></textarea>`;
    footer.innerHTML = `
      <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
      <button type="button" class="btn btn-primary" id="submitCommentBtn">发布</button>
    `;
    setTimeout(() => {
      modal.querySelector("#submitCommentBtn").onclick = function () {
        const content = modal.querySelector("#commentContent").value.trim();
        if (!content) {
          alert("请输入评价内容");
          return;
        }
        // 假设当前用户是消费者
        order.comments = order.comments || [];
        order.comments.push({
          userType: "consumer",
          avatar:
            "https://img.alicdn.com/imgextra/i4/6000000001234/O1CN01apple.jpg",
          nickname: "消费者",
          content: content,
          time: new Date().toLocaleString(),
        });
        // 关闭弹窗
        const bsModal = bootstrap.Modal.getInstance(modal);
        if (bsModal) bsModal.hide();
        // 回调（如有）
        if (onSubmit) onSubmit();
      };
    }, 0);
  }
  // 显示弹窗
  new bootstrap.Modal(modal).show();
}
